package com.dss.code_generation.util;

import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.MultiTemplateLoader;
import freemarker.cache.NullCacheStorage;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

import java.io.IOException;

/**
 * @Description:
 * @ClassName: FreeMarkerTemplateUtils
 * @author: dongshoushan
 * @date: 2020年04月20日 9:12
 */
public class FreeMarkerTemplateUtils {
    private FreeMarkerTemplateUtils(){}
    private static final Configuration CONFIGURATION = new Configuration(Configuration.VERSION_2_3_22);

    static{
        //这里比较重要，用来指定加载模板所在的路径
        ClassTemplateLoader loader = new ClassTemplateLoader(FreeMarkerTemplateUtils.class, "/templates/code");
        ClassTemplateLoader loader2 = new ClassTemplateLoader(FreeMarkerTemplateUtils.class, "/templates/docker");
        ClassTemplateLoader db = new ClassTemplateLoader(FreeMarkerTemplateUtils.class, "/templates/db");
        ClassTemplateLoader deploy = new ClassTemplateLoader(FreeMarkerTemplateUtils.class, "/templates/deploy");
        MultiTemplateLoader mtl = new MultiTemplateLoader(new TemplateLoader[] {loader,loader2,db,deploy});
        CONFIGURATION.setTemplateLoader(mtl);
        CONFIGURATION.setDefaultEncoding("UTF-8");
        CONFIGURATION.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        CONFIGURATION.setCacheStorage(NullCacheStorage.INSTANCE);
    }

    public static Template getTemplate(String templateName) throws IOException {
        try {
            return CONFIGURATION.getTemplate(templateName);
        } catch (IOException e) {
            throw e;
        }
    }
}
